package com.retry.task.core.executor;

import com.retry.task.core.constants.RetryTaskURIEnum;
import com.retry.task.core.model.HeartDTO;
import com.retry.task.core.model.RetryTaskContext;
import com.retry.task.core.model.RetryTaskDTO;
import com.retry.task.core.model.RetryTaskLogDTO;
import com.retry.task.core.model.base.Result;
import com.retry.task.core.utils.GsonTool;
import com.retry.task.core.utils.ThrowableUtils;
import io.netty.handler.codec.http.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author gao.gwq
 * @version 1.0
 * @date 2022/5/23  10:16
 * @Description TODO
 */
public class ExectorAdapterImpl implements IExectorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExectorAdapterImpl.class);

    private IExecutor iExecutor;

    public ExectorAdapterImpl(IExecutor iExecutor) {
        this.iExecutor = iExecutor;
    }

    @Override
    public Object processRequest(String requestData, String uri, HttpMethod httpMethod) {
        if (HttpMethod.POST != httpMethod) {
            return Result.getFail("100", "invalid request, request is not post.");
        }
        if (uri == null || uri.trim().length() == 0) {
            return Result.getFail("100", "invalid request, uri-mapping empty.");
        }
        try {
            if (RetryTaskURIEnum.HEART.getUri().equals(uri)) {
                HeartDTO heartDTO = GsonTool.fromJson(requestData, HeartDTO.class);
                return iExecutor.heart(heartDTO);
            }
            if (RetryTaskURIEnum.RUN.getUri().equals(uri)) {
                RetryTaskContext context = GsonTool.fromJson(requestData, RetryTaskContext.class);
                return iExecutor.run(context);
            }
            if (RetryTaskURIEnum.CALL_BACK.getUri().equals(uri)) {
                return iExecutor.callBack();
            }
            if (RetryTaskURIEnum.KILL.getUri().equals(uri)) {
                return iExecutor.killTask();
            }
            if (RetryTaskURIEnum.CREATE_RETRY_TASK.getUri().equals(uri)) {
                RetryTaskDTO retryTaskDTO = GsonTool.fromJson(requestData, RetryTaskDTO.class);
                return iExecutor.createRetryTask(retryTaskDTO);
            }
            if (RetryTaskURIEnum.UPDATE_RETRY_TASK_LOG.getUri().equals(uri)) {
                RetryTaskLogDTO retryTaskLogDTO = GsonTool.fromJson(requestData, RetryTaskLogDTO.class);
                return iExecutor.updateRetryTaskLog(retryTaskLogDTO);
            }
            return Result.getFail(Result.FAIL_CODE,
                "invalid request, uri-mapping(" + uri + ") not found.");
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return Result.getFail(Result.FAIL_CODE, "request error:" + ThrowableUtils.toString(e));
        }
    }

}
